import { Component, ChangeDetectionStrategy, Input, NgZone, ChangeDetectorRef, ElementRef } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd';
import { format } from 'date-fns';
import { parseDateStr } from '@shared';

/**
 * 销售周报折线图
 */
@Component({
  selector: 'app-prod-saleweek',
  templateUrl: './prod-saleweek-line.component.html',
  styleUrls: ['./prod-saleweek-line.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '[class.card]': 'true',
  },
})
export class ProdSaleWeekLineComponent {
  noData = true;

  @Input()
  title = '';

  @Input()
  set codeName(val) {
    if (val) {
      this._codeName = val;
      this.http.get(`/cf/prod/sys-prod/prodyear/getbyCodeName?codeName=${this._codeName}`).subscribe(res => {
        if (res.status === 200) {
          this.i.start = parseDateStr(res.data.startTime);
          this.i.end = parseDateStr(res.data.endTime);
          this.attachData(this._codeName);
        }
      });
    }
  }

  widthConfig = ['100px', '150px', '150px', '150px', '150px', '150px', '150px', '150px', '150px', '150px', '150px'];
  scrollConfig = { x: '1200px' };

  _codeName = null;
  loading = true;
  data = [];
  table = {};
  time = null;
  chart: any;
  showType = 'chart';
  cols = [];
  i = { start: null, end: null };

  constructor(
    public http: _HttpClient,
    public msg: NzMessageService,
    private ngZone: NgZone,
    private cdr: ChangeDetectorRef,
  ) {}

  render(er: ElementRef) {
    this.ngZone.runOutsideAngular(() => setTimeout(() => this.init(er.nativeElement), 50));
  }

  private init(container: HTMLElement) {
    const chart = (this.chart = new G2.Chart({
      container,
      forceFit: true,
      height: 400,
      padding: [30, 170, 70, 50],
    }));

    chart.source(this.data.filter(r => r.type !== '销售倍数'));
    chart.scale({
      date: {
        type: 'cat',
        tickCount: 20,
      },
    });
    chart.axis('date', {
      label: {
        textStyle: {
          fill: '#aaaaaa',
        },
      },
    });
    chart.axis('value', {
      label: {
        textStyle: {
          fill: '#aaaaaa',
        },
        formatter: function formatter(text) {
          return text.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
        },
      },
    });
    chart.legend({
      attachLast: true,
    });
    chart
      .line()
      .position('date*value')
      .color('type')
      .size(2);
    chart.render();
  }

  private attachData(codeName) {
    const { chart, ngZone } = this;
    ngZone.run(() => {
      this.loading = true;
      this.cdr.detectChanges();
    });

    const endDate = format(this.i.end, 'YYYY-MM-DD');
    const startDate = format(this.i.start, 'YYYY-MM-DD');

    this.http.post(`/cf/report/prod/saleweek/${codeName}`, { startDate, endDate }).subscribe((res: any) => {
      ngZone.run(() => {
        this.data = [];
        this.cols = [];
        this.table = {};
        this.noData = true;
        if (res.data && res.data.length > 0) {
          this.noData = false;
          this.data = res.data;
          this.data.forEach(r => {
            if (this.cols.indexOf(r.date) < 0) {
              this.cols.push(r.date);
            }
            if (this.table[r.type]) {
              this.table[r.type].push(r.value);
            } else {
              this.table[r.type] = [r.value];
            }
          });
        }
        this.time = new Date();
        this.loading = false;
        this.cdr.detectChanges();
      });
    });
  }

  /**
   * 日期变更
   */
  onDateChange(v) {
    if (!v) {
      this.attachData(this._codeName);
    }
  }
}
